package com.cn.shuangzi.util;

import android.os.Environment;
import android.text.TextUtils;
import android.util.Base64;

import com.cn.shuangzi.SZApp;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;


public class SZFileUtil {
    private static SZFileUtil fileCache;
    private File imgFile;
    private File tmpFile;
    private File downloadFile;
    private File apkFile;
    private File cacheFile;

    private SZFileUtil() {
        // 如果有SD卡则在SD卡中建一个目录存放缓存的图片
        // 没有SD卡就放在系统的缓存目录中
        try {
            cacheFile = SZApp.getInstance().getExternalCacheDir();
            imgFile = new File(cacheFile, "imgCache");
            tmpFile = new File(cacheFile, "tmp");
            downloadFile = new File(cacheFile, "download");
            apkFile = new File(downloadFile, "apk");
            if (!cacheFile.exists()) {
                cacheFile.mkdirs();
            }
            if (!imgFile.exists()) {
                imgFile.mkdirs();
            }
            if (!tmpFile.exists()) {
                tmpFile.mkdirs();
            }
            if (!downloadFile.exists()) {
                downloadFile.mkdirs();
            }
            if (!apkFile.exists()) {
                apkFile.mkdirs();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static SZFileUtil resetInstance() {
        fileCache = new SZFileUtil();
        return fileCache;
    }

    public static SZFileUtil getInstance() {
        if (fileCache == null) {
            fileCache = new SZFileUtil();
        }
        return fileCache;
    }

    public String getTmpPathName() {
        return tmpFile.getAbsolutePath();
    }

    public File getOneTmpPic() {
        return new File(tmpFile, "tmp.jpg");
    }

    public void clearTmpFiles() {
        clearFile(tmpFile);
    }

    // 获得缓存目录
    public File getCacheFile() {
        return cacheFile;
    }

    // 获得图片缓存目录
    public File getImgCacheFile() {
        return imgFile;
    }

    public String getImgCacheFilePath() {
        return imgFile.getAbsolutePath();
    }
//	public String getSkinsPathName(){
//		return skinsFile.getAbsolutePath();
//	}

    // 获得下载路径
    public String getDownloadPathName() {
            return downloadFile.getAbsolutePath();
    }

    public File getApkPathName() {
        return apkFile.getAbsoluteFile();
    }
    // 是否有SD卡
    public boolean hasSDCard() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    // 按照文件夹获取该文件夹大小
    public String getCacheFileSizeByFolder(String folder) {
        try {
            return formatFileSize(getFileSize(new File(folder)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    // 获得缓存文件夹大小
    public String getCacheFileSize() {
        try {
            return formatFileSize(getFileSize(cacheFile));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public String getAllCacheFileSize() {
//        return formatFileSize(getFileSize(getCacheFile()) + getFileSize(getImgCacheFile()));
        return formatFileSize(getFileSize(getCacheFile()));
    }

    public void clearAllCacheFile() {
        clearImgCacheFiles();
        clearCacheFiles();
    }

    /**
     * 获得文件夹下的文件
     *
     * @param f
     * @return
     */
    public File[] getFilesByFolder(File f) {
        File flist[] = f.listFiles();
        return flist;
    }

    // 递归
    public long getFileSize(File f)// 取得文件夹大小
    {
        long size = 0;
        try {
            File fileList[] = f.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                if (fileList[i].isDirectory()) {
                    size = size + getFileSize(fileList[i]);
                } else {
                    size = size + fileList[i].length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    public String formatFileSize(long fileS) {// 转换文件大小
        if (fileS == 0)
            return "";
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "K";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "G";
        }
        return fileSizeString;
    }

    /**
     * *******************
     * 清空制定缓存文件夹
     *
     * @param folder *******************
     */
    public void clearCacheFiles(String folder) {
        try {
            File[] files = new File(cacheFile.getAbsolutePath() + "/" + folder)
                    .listFiles();
            if (files == null)
                return;
            for (File f : files)
                f.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * *******************
     * 清空图片缓存文件夹
     * *******************
     */
    public void clearImgCacheFiles() {
        clearFile(imgFile);
    }

    /**
     * *******************
     * 清空文件下载文件夹
     * *******************
     */
    public void clearDownloadFiles() {
        clearFile(downloadFile);
    }
    /**
     * *******************
     * 清空APK下载缓存文件夹
     * *******************
     */
    public void clearApkFiles() {
        clearFile(apkFile);
    }

    /**
     * *******************
     * 清空所有缓存文件夹
     * *******************
     */
    public void clearCacheFiles() {
        clearFile(cacheFile);
    }

    public void clearFile(File file) {
        File[] fileList = file.listFiles();
        if (fileList != null) {
            for (int i = 0; i < fileList.length; i++) {
                if (fileList[i].isDirectory()) {
                    clearFile(fileList[i]);
                } else {
                    fileList[i].delete();
                }
            }
        }
    }

    /**
     * 把文件拷贝到某一目录下,并删除源文件
     *
     * @param srcFile
     * @param destDir
     * @return
     */
    public boolean moveFileToDir(String srcFile, String destDir) {
        File fileDir = new File(destDir);// 目标文件
        File fileSrc = new File(srcFile);// 源文件
        if (!fileDir.exists()) {
            fileDir.mkdir();
        }
        String destFile = destDir + "/" + fileSrc.getName();
        try {
            InputStream streamFrom = new FileInputStream(srcFile);
            OutputStream streamTo = new FileOutputStream(destFile);
            byte buffer[] = new byte[1024];
            int len;
            while ((len = streamFrom.read(buffer)) > 0) {
                streamTo.write(buffer, 0, len);
            }
            streamFrom.close();
            streamTo.close();
            fileSrc.delete();
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    /**
     * 将图片转换成Base64编码的字符串
     */
    public static String imageToBase64(String path, int flags) {
        if (TextUtils.isEmpty(path)) {
            return null;
        }
        InputStream is = null;
        byte[] data = null;
        String result = null;
        try {
            is = new FileInputStream(path);
            //创建一个字符流大小的数组。
            data = new byte[is.available()];
            //写入数组
            is.read(data);
            result = Base64.encodeToString(data, flags);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return result;
    }

    /**
     * 将图片转换成Base64编码的字符串
     */
    public static String imageToBase64(String path) {
        return imageToBase64(path, Base64.NO_WRAP);
    }

    public static byte[] getBytesByFile(String filePath) {
        try {
            File file = new File(filePath);
            //获取输入流
            FileInputStream fis = new FileInputStream(file);
            byte[] data = new byte[fis.available()];
            fis.read(data);
            fis.close();
            return data;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static File getFileByBytes(byte[] bytes, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            // 判断文件目录是否存在
            if (!dir.exists() && dir.isDirectory()) {
                dir.mkdirs();
            }
            file = new File(filePath + "\\" + fileName);

            //输出流
            fos = new FileOutputStream(file);

            //缓冲流
            bos = new BufferedOutputStream(fos);

            //将字节数组写出
            bos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }
}
